import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:heven/model/config_model.dart';
import 'package:heven/pages/home/widget/cd/empty.dart';
import 'package:heven/pages/home/widget/cd/user.dart';
import 'package:heven/pages/home/widget/cd/song.dart';
import 'package:heven/pages/home/widget/title.dart';
import 'package:heven/pages/home/widget/cd/vip.dart';
import 'package:heven/api/index.dart';
import 'package:heven/utils/index.dart';
import 'package:provider/provider.dart';
import 'package:heven/state/music.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CdWidget extends StatefulWidget {
  const CdWidget({super.key});

  @override
  State<CdWidget> createState() => _CdWidgetState();
}

class _CdWidgetState extends State<CdWidget>
    with AutomaticKeepAliveClientMixin {
  final bool value = false;
  var user = {};
  List list = [];
  bool isLoadingMore = false;
  var uid = '';
  int _isTourist = 1;
  int coin = 0;

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  Timer? _statusCheckTimer;

  @override
  bool get wantKeepAlive => true; // 保持页面状态

  @override
  void initState() {
    super.initState();

    _fetchData();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    _statusCheckTimer?.cancel(); // 取消定时器
    super.dispose();
  }

  Future<void> _fetchData() async {
    // String? artConsumeCoinNumberString =
    //     await Common.getStorageValue('artConsumeCoinNumber');
    // int artConsumeCoinNumber =
    //     int.tryParse(artConsumeCoinNumberString ?? '1') ?? 1;

    uid = await Common.getStorageValue('uid') ?? ''; // 提供默认值或处理 null

    if (uid.isEmpty) {
      return;
    }
    var result = await getConfig();
    print("result:${result}");
    // ConfigModel configModel = ConfigModel.fromJson(result);
    await getProfile({"uid": uid}).then((value) {
      print(value);
      setState(() {
        user = value['data'] ?? {};
        coin = ((user['coin'] + user['vip_coin']) /
                result['art_consume_coin_number']['value'])
            .floor();
        _isTourist = user['is_tourist'] ?? 0;
      });
      Common.saveStorageValue("isVip", value['data']['is_vip'].toString());
    }).catchError((error) {
      // 处理错误
      print('Error fetching data3: $error');
    });

    await _loadInitialData(uid);
  }

  Future<void> _loadInitialData(String uid) async {
    if (isLoadingMore) return; // 如果已经在加载，则不重复加载

    setState(() {
      isLoadingMore = true;
    });

    await mymusic({
      "uid": uid,
      "limit": "30",
    }).then((value) {
      setState(() {
        list = value['data']['list'] as List; // 初始化列表
        isLoadingMore = false;
      });

      if (_hasPendingStatus()) {
        _startStatusCheck(); // 存在时启动状态检查
      }
    }).catchError((error) {
      // 处理错误
      setState(() {
        isLoadingMore = false;
      });
      print('Error fetching data1: $error');
    });
  }

  Future<void> _loadInitialData1(String uid) async {
    if (isLoadingMore) return; // 如果已经在加载，则不重复加载

    setState(() {
      isLoadingMore = true;
    });

    await mymusic({
      "uid": uid,
      "limit": "30",
    }).then((value) {
      List newList = value['data']['list'] as List;

      // 仅当新数据与旧数据不同才更新列表和重渲染页面
      var mark = 0;
      for (int i = 0; i < newList.length; i++) {
        if (list[i]['status'] != newList[i]['status']) {
          list[i] = newList[i];
          mark = 1;
        }
      }

      setState(() {
        isLoadingMore = false;
      });
    }).catchError((error) {
      // 处理错误
      setState(() {
        isLoadingMore = false;
      });
      print('Error fetching data1: $error');
    });
  }

  void _startStatusCheck() {
    _statusCheckTimer?.cancel(); // 防止重复启动定时器
    _statusCheckTimer = Timer.periodic(Duration(seconds: 20), (timer) async {
      if (_hasPendingStatus()) {
        print(1222);
        await _loadInitialData1(uid);
      } else {
        print(1333);
        _statusCheckTimer?.cancel(); // 若无 pending 状态则停止定时器
      }
    });
  }

  bool _hasPendingStatus() {
    return list.any((item) => item['status'] == 1);
  }

  void _onRefresh() async {
    // monitor network fetch

    // if failed,use refreshFailed()
    await _fetchData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    await _loadMoreData(uid);
    _refreshController.loadComplete();
  }

  _loadMoreData(String uid) async {
    if (isLoadingMore) return; // 如果已经在加载，则不重复加载

    setState(() {
      isLoadingMore = true;
    });

    int? lastId;
    if (list.isNotEmpty) {
      lastId = list.last['id']; // 获取最后一个元素的 id
    }

    await mymusic({
      "uid": uid,
      "limit": "30",
      "minId": lastId?.toString(), // 使用最后一个元素的 id
    }).then((value) {
      setState(() {
        list.addAll(value['data']['list'] as List);
        isLoadingMore = false;
      });
      _refreshController.loadComplete();
    }).catchError((error) {
      // 处理错误
      setState(() {
        isLoadingMore = false;
      });
      print('Error fetching data2: $error');
    });
  }

  void _callback(String id) {
    var data = list.firstWhere((element) => element['id'].toString() == id,
        orElse: () => null);
    if (data != null) {
      list.remove(data);
      setState(() {});
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 保持页面状态
    return Scaffold(
      backgroundColor: const Color(0xFF010101),
      appBar: AppBar(
        toolbarHeight: 50.0,
        backgroundColor: const Color(0xFF010101),
        actions: [
          Container(
            margin: const EdgeInsets.only(right: 15),
            child: GestureDetector(
              onTap: () async {
                Navigator.pushNamed(context, '/set',
                    arguments: {"isTourist": _isTourist});
              },
              child: Image.asset(
                'assets/images/set.png',
                width: 21,
                height: 24,
              ),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          UserWidget(
            userName: user['nickname'] ?? '',
            isTourist: _isTourist,
          ),
          VipWidget(
            isVip: user['is_vip'] ?? false,
            coin: coin,
          ),
          const TitleWidget(title: '我的音乐'),
          Expanded(
            flex: 1,
            child: list.length == 0
                ? const Stack(
                    children: [EmptyWidget()],
                  )
                : SmartRefresher(
                    enablePullDown: true,
                    enablePullUp: list.length >= 30,
                    controller: _refreshController,
                    onRefresh: _onRefresh,
                    onLoading: _onLoading,
                    header: CustomHeader(
                        builder: (BuildContext context, RefreshStatus? mode) {
                      Widget body;
                      if (mode == RefreshStatus.idle) {
                        body = const Text(
                          "下拉拉加载",
                          style: TextStyle(color: Colors.white),
                        );
                      } else if (mode == RefreshStatus.failed) {
                        body = const Text("加载失败！点击重试！",
                            style: TextStyle(color: Colors.white));
                      } else if (mode == RefreshStatus.canRefresh) {
                        body = const Text("松手,刷新!",
                            style: TextStyle(color: Colors.white));
                      } else {
                        body = const CupertinoActivityIndicator(
                          color: Colors.white,
                        );
                      }
                      return Container(
                        height: 55.0,
                        child: Center(child: body),
                      );
                    }),
                    footer: CustomFooter(
                        builder: (BuildContext context, LoadStatus? mode) {
                      Widget body;
                      if (mode == LoadStatus.idle) {
                        body = Text("上拉加载");
                      } else if (mode == LoadStatus.loading) {
                        body = CupertinoActivityIndicator();
                      } else if (mode == LoadStatus.failed) {
                        body = Text("加载失败！点击重试！");
                      } else if (mode == LoadStatus.canLoading) {
                        body = Text("松手,加载更多!");
                      } else {
                        body = Text("没有更多数据了!");
                      }
                      return Container(
                        height: 55.0,
                        child: Center(child: body),
                      );
                    }),
                    child: ListView.builder(
                      itemBuilder: (c, i) {
                        var item = list[i];
                        return SongWidget(
                          key: ValueKey(item['id']),
                          imgUrl: item['image_url'] ?? '',
                          name: item['title'] ?? '',
                          subheading: item['tags'] ?? '',
                          status: item['status'],
                          showBottomSheet: () {
                            _showBottomSheet(
                                context, item['id'].toString(), _callback);
                          },
                          onTap: () async {
                            if (item['status'] == 1 || item['status'] == 3) {
                              return;
                            }
                            final musicState = context.read<MusicState>();
                            if (musicState.type == 1 || musicState.type == 2) {
                              musicState.setType(3);
                              final convertedList =
                                  list.map<Map<String, String>>((item) {
                                // 确保键和值都被转换为 String 类型
                                return item.map<String, String>((key, value) {
                                  return MapEntry(
                                      key.toString(), value.toString());
                                });
                              }).toList();
                              musicState.setPlaylist(convertedList);
                            }
                            final convertedItem =
                                item.map<String, String>((key, value) {
                              return MapEntry(key.toString(), value.toString());
                            });
                            WidgetsBinding.instance.addPostFrameCallback((_) {
                              musicState.setCurrentSong(convertedItem);
                            });
                            // 跳转到播放页面
                            // Navigator.pushNamed(context, '/music');
                            final songDeleted =
                                await Navigator.pushNamed(context, '/music');
                            if (songDeleted == true) {
                              // 如果返回的是true，则刷新数据
                              _loadInitialData(uid);
                            }
                          },
                        );
                      },
                      itemExtent: 100.0,
                      itemCount: list.length,
                    ),
                  ),
          )
        ],
      ),
    );
  }
}

_showBottomSheet(BuildContext context, String id, Function callback) {
  showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.zero, // 去掉圆角
      ),
      builder: (BuildContext context) {
        return Container(
          height: 145,
          width: double.infinity,
          child: Column(
            children: [
              GestureDetector(
                child: Container(
                  alignment: Alignment.center,
                  height: 72,
                  width: double.infinity,
                  decoration: const BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        color: Color(0xFFCFCFCF),
                      ),
                    ),
                  ),
                  child: const Text(
                    '删除作品',
                    style: TextStyle(
                      color: Color(0xFF001CFF),
                      fontSize: 14,
                    ),
                  ),
                ),
                onTap: () async {
                  final uid = await Common.getStorageValue('uid');
                  final result = await delmusic({"id": id, "uid": uid});
                  if (result['status'] == 200) {
                    callback(id);
                  }
                },
              ),
              GestureDetector(
                child: Container(
                  alignment: Alignment.center,
                  height: 72,
                  width: double.infinity,
                  child: const Text(
                    '退出',
                    style: TextStyle(
                      color: Color(0xFF001CFF),
                      fontSize: 14,
                    ),
                  ),
                ),
                onTap: () {
                  print('退出');
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        );
      });
}
